import smtplib
from email.mime.text import MIMEText
from email.header import Header
from config.mail_config import EmailSettings

# 实例化配置
email_settings = EmailSettings()


def send_email(
    to_email: str,
    subject: str,
    content: str,
    is_html: bool = False
):
    """
    发送邮件
    :param to_email: 收件人邮箱
    :param subject: 邮件主题
    :param content: 邮件内容
    :param is_html: 是否为HTML内容
    """
    msg = MIMEText(content, "html" if is_html else "plain", "utf-8")
    msg["From"] = email_settings.MAIL_DEFAULT_SENDER # 发件人
    msg["To"] = to_email# 收件人
    msg["Subject"] = Header(subject, "utf-8")  # 主题

    try:
        # 连接邮件服务器并发送
        if email_settings.MAIL_USE_SSL:
            # SSL加密连接
            server = smtplib.SMTP_SSL(
                email_settings.MAIL_SERVER,
                email_settings.MAIL_PORT
            )
        else:
            # 非加密连接（不推荐）
            server = smtplib.SMTP(
                email_settings.MAIL_SERVER,
                email_settings.MAIL_PORT
            )
            server.starttls()  # 启用TLS加密（若使用587端口）

        # 登录邮箱
        server.login(
            email_settings.MAIL_USERNAME,
            email_settings.MAIL_PASSWORD
        )

        # 发送邮件（注意：sendmail的参数为 发件人、收件人列表、邮件内容）
        server.sendmail(
            email_settings.MAIL_DEFAULT_SENDER,
            [to_email],
            msg.as_string()
        )

        # 关闭连接
        server.quit()
        return {"status": "success", "message": "邮件发送成功"}

    except Exception as e:
        return {"status": "error", "message": f"邮件发送失败：{str(e)}"}